package com.katesoft.scale4j.persistent.utils;

import com.katesoft.scale4j.common.utils.Enumerator;
import com.katesoft.scale4j.log.LogFactory;
import org.apache.log4j.Appender;
import org.perf4j.StopWatch;
import org.perf4j.log4j.AsyncCoalescingStatisticsAppender;
import org.perf4j.log4j.GraphingStatisticsAppender;

import java.util.Collection;

/**
 * This is utility class for pef4j.
 *
 * @author kate2007
 */
public class Perf4jLoggerUtility
{
    /** @return all appenders for {@link StopWatch#DEFAULT_LOGGER_NAME} logger or <code>NULL</code>. */
    public static Enumerator<Appender> allAppenders()
    {
        return LogFactory.getAllAppenders(StopWatch.DEFAULT_LOGGER_NAME);
    }

    /**
     * looking for standard {@link AsyncCoalescingStatisticsAppender} appender.
     * <p/>
     * Most applications that are using perf4j will definitely use this appender.
     *
     * @return first found AsyncCoalescingStatisticsAppender or <code>NULL</code>.
     */
    public static AsyncCoalescingStatisticsAppender findAsyncCoalescingStatisticsAppender()
    {
        Enumerator<Appender> enumerator = allAppenders();
        if (enumerator != null) {
            while (enumerator.hasNext()) {
                Appender appender = enumerator.next();
                if (appender instanceof AsyncCoalescingStatisticsAppender) {
                    return (AsyncCoalescingStatisticsAppender) appender;
                }
            }
        }
        return null;
    }

    /** @return collection of {@code GraphingStatisticsAppender} appenders of perf4j logger. */
    public static Collection<GraphingStatisticsAppender> findGraphingStatisticsAppender()
    {
        return GraphingStatisticsAppender.getAllGraphingStatisticsAppenders();
    }

    private Perf4jLoggerUtility() {}
}
